<?php
namespace app\admin\controller;
use app\admin\model\SystemConfig;
use app\admin\model\SystemUploadfile;
use app\common\controller\AdminController;
use app\common\model\ArticleAttribute;
use app\common\model\PaymentAccount;
use app\common\model\Service;
use app\common\service\MailService;
use app\common\service\MenuService;
use app\common\service\SmsService;
use app\common\service\UploadService;
use app\common\service\TransferService;
use think\db\Query;
use think\facade\Cache;
use app\common\library\Watermark;

class Ajax extends AdminController
{

    /**
     * 初始化后台接口地址
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function initAdmin()
    {
        $cacheData = Cache::get('initAdmin_' . session('admin.id'));
        if (!empty($cacheData)) {
            return json($cacheData);
        }
        $menuService = new MenuService(session('admin.id'));
        $data = [
            'logoInfo' => [
                'title' => sysconfig('site', 'site_name'),
                'image' => sysconfig('site', 'logo_image'),
                'href' => __url('index/index'),
            ],
            'homeInfo' => $menuService->getHomeInfo(),
            'menuInfo' => $menuService->getMenuTree(),
        ];
        Cache::tag('initAdmin')->set('initAdmin_' . session('admin.id'), $data);
        return json($data);
    }

    public function check_update()
    {
        $find = (new SystemConfig())->where('name', 'version')->find();
        if (!$find) {
            $version = 'j/0Afx6Ep5NJtGr0+NGiHBWg7MCodoxSmiKDkPS1z6D04Cpd2DTj9kaTwYYmDLX1u6kJvpt8E9Vnc2J/uKpfUN/mOjU1UTODOLnwQfAK75WqgC02UQyKMT+hUz2lm/IW';
            (new SystemConfig())->save([
                'name' => 'version',
                'value' => $version
            ]);
        } else {
            $version = $find['value'];
        }
        $updKey = env('key');
        if ($updKey && strlen($updKey) != 32) {
            return fail('没有争取配置KEY，请打开根目录.env配置');
        }
        return \org\Laysns::checkUpdate($version);
    }

    public function updates()
    {
        $key = env('key');
        if (!$key) {
            return fail('没有配置KEY');
        }
        $params = $this->request->param();
        return \org\Laysns::update($params['type'],$params['ver_id']);

    }







    /**
     * 清理缓存接口
     */
    public function clearCache()
    {
        Cache::clear();
        authCheck();
        $this->success('清理缓存成功');
    }

    public function getShouPayments()
    {
        $jieshi = [
            'alipay' => '支付宝',
            'wxpay' => '微信支付',
            'qqpay' => 'QQ钱包支付',
        ];
        $arr = PaymentAccount::getShouPayments();
        $pays = [];
        foreach ($arr as $k => $v) {
            $pays[] = [
                'id' => $k,
                'title' => $jieshi[$k],
            ];
        }
        return success('success', $pays);

    }

    public function getFuPayments()
    {

    }

    /**
     * 上传文件
     */
    public function upload()
    {
        $File = $this->request->file('file');
        $data = $this->request->param();
        $watermark  = $thumb = '';
        $uplodeType='local';
        if (isset($data['watermark'])) {
            $watermark = $data['watermark'];
        }
        if (isset($data['upload_type'])&&$data['upload_type']) {
            $uplodeType = $data['upload_type'];
        }
        if (isset($data['thumb'])) {
            $thumb = $data['thumb'];
        }
        return UploadService::upfile($File, '', $watermark, $thumb);
    }

    /**
     * 上传图片至编辑器
     * @return \think\response\Json
     */
    public function editorUploadImg()
    {
        $files = $this->request->file();
        $imags = [];
        $errors = [];
        $k = 0;
        $uploadConfig = sysconfig('upload');
        $maxSize = $uploadConfig['upload_allow_size'] * 1024 * 1024;
        $rule = [
            'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$maxSize}",
        ];
        foreach ($files as $file) {
            try {
                $this->validate(['file' => $file], $rule);
            } catch (\Exception $e) {
                array_push($errors, '文件大小或后缀不支持');
                continue;
            }
            $fileName = $file->getOriginalName();
            $picThumb = sysconfig('upload.picture_thumb_max');
            $res = UploadService::upfile($file, '', 1, $picThumb ? $picThumb : 700);
            if ($res['code'] == 1) {
                array_push($imags, [
                    'url' => $res['data']['url'],
                    'alt' => $fileName
                ]);
                $k++;
            } else {
                array_push($errors, @$res['msg']);
                continue;
            }
        }
        if (!empty($imags)) {
            $ret['errno'] = 0;
            $ret['data'] = $imags;
        } else {
            $ret['errno'] = 1;
            $ret['data'] = [];
            $ret['msg'] = "上传出错：" . implode('；', $errors);
        }
        return json($ret);
    }

    /**
     * 上传非图片（VIDEO）至编辑器
     * @return \think\response\Json
     */
    public function editorUploadFile()
    {
        $file = $this->request->file('file');
        $res = UploadService::upfile($file, '', 0, 0);
        if ($res['code'] == 1) {
            $res['errno'] = 0;
        } else {
            $ret['errno'] = 1;
        }
        return json($res);
    }

    /**
     * 获取上传文件列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUploadFiles()
    {
        $get = $this->request->get();
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 10;
        $title = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $this->model = new SystemUploadfile();
        $count = $this->model
            ->where('mime_type', 'like', 'image%')
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->count();
        $list = $this->model
            ->where('mime_type', 'like', 'image%')
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->page($page, $limit)
            ->order($this->sort)
            ->select();
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $list,
        ];
        return json($data);
    }

    public function sendmail()
    {
        $data = $this->request->post();
        if (!isset($data['subject'])) {
            $data['subject'] = '测试邮件';
            $arr = explode("\n", $data['admin_email']);
            $data['to_email'] = $arr[0];
        }
        return MailService::sendEmail($data['to_email'], $data['subject'], 'TEST');
    }

    public function sendsms()
    {
        $data = $this->request->post();
        $res = SmsService::sendSms($data['admin_phone'], 'TEST');
        return json($res);
    }


    public function reward(){
        $data = $this->request->post();
        $item=(new ArticleAttribute())->find($data['id'])->toArray();
        if($item['reward_status']!=0){
            return fail('已经奖励过了');
        }
        $item['amount']=$data['reward_amount'];
        $item['remark']='奖励';
        $res=TransferService::dopay($item);

            if($res['status']==1){
                (new ArticleAttribute())->where('id',$data['id'])
                    ->update([
                            'reward_status'=>1,
                            'reward_result'=>$res['msg'],
                            'reward_amount'=>$data['reward_amount'],
                    ]);
                return success($res['msg']);
            }else {
                return fail($res['msg']);
            }
    }
}